package com.xishu.service.close.shop;


import com.xishu.entity.order.Order;
import com.xishu.entity.shop.Shop;
import com.xishu.service.order.base.OrderService;
import com.xishu.service.ShopService;
import com.xishu.service.StripeService;
import com.xishu.util.ClassUtil;
import com.xishu.util.Tools;

import java.util.List;
import java.util.stream.Collectors;

public class CloseShopService implements Tools {
    private static CloseShopService instance = new CloseShopService();

    private CloseShopService() {
    }

    public static CloseShopService getInstance() {
        return instance;
    }

    /**
     * 检查小费
     *
     * @param shopId
     */
    public Order checkTips(Long shopId) throws Exception {
        Shop shop = ShopService.getInstance().findShopById(shopId);

        List<Order> orderList = OrderService.getInstance().findStripeTerminalPayedOrder(shopId);

        //过滤有小费的订单
        orderList = orderList.stream().filter(order -> getDouble(order.getTipsFee()) > 0).collect(Collectors.toList());

        //依次去核对小费
        for (Order order : orderList) {
            //找到支付订单，然后做capture操作
            if (getBoolean(order.getParentOrder())) {
                List<Order> payedOrderList = OrderService.getInstance().findOrderByParentId(order.getId(), order.getShopId())
                        .stream().filter(p -> getBoolean(p.getPayed()) && !getBoolean(p.getReturnCash())).collect(Collectors.toList());

                for (Order payedOrder : payedOrderList) {
                    payedOrder = (Order)ClassUtil.clone(payedOrder);
                    boolean capture = StripeService.getInstance().capture(payedOrder, shop);
                    if (!capture) {
                        payedOrder.setTipsFee(order.getTipsFee());
                        return payedOrder;
                    }
                }
            } else {
                //子订单处理，也需要找到支付订单，然后做capture操作
                Order payedOrder = OrderService.getInstance().findPayOrderWithSubOrderId(order).stream().filter(p -> getBoolean(p.getPayed()) && !getBoolean(p.getCancel())).findAny().get();
                payedOrder = (Order)ClassUtil.clone(payedOrder);
                boolean capture = StripeService.getInstance().capture(payedOrder, shop);
                if (!capture) {
                    payedOrder.setTipsFee(order.getTipsFee());
                    return payedOrder;
                }
            }
        }

        return new Order();
    }
}
